﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using SXICE.AdminAPI.Utilities;
using SXICE.IService;
using System;
using System.Linq;

namespace SXICE.AdminAPI.Filters
{
    /// <summary>
    /// 权限校验过滤器
    /// </summary>
    public class AuthorizationRightsAttribute : IAuthorizationFilter
    {
        private readonly IRightsService rightsService;
        private readonly IDoctorService doctorService;

        public AuthorizationRightsAttribute(IRightsService rightsService, IDoctorService doctorService)
        {
            this.rightsService = rightsService;
            this.doctorService = doctorService;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var des = context.ActionDescriptor as ControllerActionDescriptor;
            var rightsAttribute = des.MethodInfo.GetCustomAttributes(typeof(RightsAttribute), false).FirstOrDefault();
            if (null != rightsAttribute)
            {
                var code = (rightsAttribute as RightsAttribute).code;
                var result = rightsService.HasRights(WorkContext.DoctorClaims.RoleId, code);
                if (!result.Success)
                {
                    context.Result = new OkObjectResult(result);
                    return;
                }
                result = doctorService.IsEnabled(WorkContext.DoctorClaims.UserId);
                if (!result.Success)
                    context.Result = new OkObjectResult(result);
            }
        }
    }

    /// <summary>
    /// 权限属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class RightsAttribute : Attribute
    {
        public readonly string code;

        public RightsAttribute(string code)
        {
            this.code = code;
        }
    }
}
